﻿using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows.Input;
using AutoCADDotNetLibrary;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Geometry;

namespace Test
{
    public class MVVMXDataPaletteViewModel : IReadEntityEvent
    {
        public ObservableCollection<MVVMXDataPaletteModel> Models { get; } = new ObservableCollection<MVVMXDataPaletteModel>();

        private Document _doc;

        #region IReadEntityEvent

        public bool IsUseEvent { get; set; } = true;

        public void ReadEntities(Document doc, Entity[] ents)
        {
            _doc = doc;

            Models.Clear();
            foreach (Entity ent in ents)
            {
                MVVMXDataPaletteModel d = ent.GetModelByXdata<MVVMXDataPaletteModel>();
                if (d != null)
                {
                    d.Id = ent.Id;
                    Models.Add(d);
                }
            }
        }

        #endregion

        public ICommand CreateLineCommand => new RelayCommand(() => SimpleAutoCADAOP.RunUIMethod(_createLine, true));

        private void _createLine(Document doc)
        {
            if (Application.DocumentManager.MdiActiveDocument != _doc)
                return;

            int? count = doc.Editor.Get<int>("数量") as int?;
            if (count == null)
                return;

            doc.Database.AddTableRecord<RegAppTableRecord>("Model");

            List<Line> ls = Enumerable.Range(0, count.Value).Select(x =>
            {
                Line l = new Line(new Point3d(0 + x * 100, 0, 0), new Point3d(300 + x * 100, 300, 0));
                l.SetXdataByModel<MVVMXDataPaletteModel>(new MVVMXDataPaletteModel() { Name = "name", Value = "value" });
                return l;
            }).ToList();
            doc.Database.AddEntityToSpace(Space.CurrentSpace, true, ls.ToArray());
        }
    }
}
